package com.example.phonefinder;

import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Settings extends Activity implements OnClickListener {
	
	private Button startServiceButton;
	private Button stopServiceButton;
	private String m_secretPhrase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        
        startServiceButton = (Button) findViewById(R.id.buttonStart);
        stopServiceButton = (Button) findViewById(R.id.buttonStop);
        
        startServiceButton.setOnClickListener(this);
        stopServiceButton.setOnClickListener(this);
        
        m_secretPhrase = "Hello";
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_settings, menu);
        return true;
    }
    
    private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (PhoneFinderService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if (arg0.getId() == startServiceButton.getId())
		{
			Log.d("Settings", "Start Service clicked.");
			if (isMyServiceRunning())
			{
				Log.d("Settings", "The Service is running.");
			}
			Intent serviceIntent = new Intent(Settings.this,PhoneFinderService.class);
			serviceIntent.putExtra("Secret Phrase", m_secretPhrase);
			startService(serviceIntent);
		}
		else if (arg0.getId() == stopServiceButton.getId())
		{
			Log.d("Settings", "Stop Service clicked");
			if (isMyServiceRunning())
			{
				Log.d("Settings", "The Service is running.");
			}
			stopService(new Intent(Settings.this,PhoneFinderService.class));
		}
	}
}
